package com.dfbz.dao;

import com.dfbz.entity.Meeting;
import org.springframework.jdbc.core.BeanPropertyRowMapper;

import java.util.List;
import java.util.Map;

public class MeetingDao extends BaseDao {

    public Integer findMeetCount(String title, long status) {
            String sql;
            if (status != -1) {
                sql = "select count(1) from meeting where title like concat('%',?,'%') and `status` = ?";
                return jdbcTemplate.queryForObject(sql, Integer.class, title, status);
            } else {
                sql = "select count(1) from meeting where title like concat('%',?,'%')";
                return jdbcTemplate.queryForObject(sql, Integer.class, title);
            }
    }

    public List<Meeting> findAll(Long status, String title, int startIndex, Integer pageSize) {
        String sql;
        if (status != -1) {
            sql = "select * from meeting where title like concat('%',?,'%') and `status` = ? order by publish_date desc limit ?,?";
            return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Meeting.class), title, status, startIndex, pageSize);
        } else {
            sql = "select * from meeting where title like concat('%',?,'%') order by publish_date desc limit ?,?";
            return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Meeting.class), title, startIndex, pageSize);
        }
    }

    public List<Map<String, Object>> findMeetingById(Long id) {
        return jdbcTemplate.queryForList("select m.*,d.name from meeting m join dept d on m.dept_id = d.id where m.id = ?",id);
    }

    public String findMeetingMakeUserById(Long id) {
        return jdbcTemplate.queryForObject("select make_user from meeting where id = ?",String.class,id);
    }

    public Long findReaComCount(Long id) {
            return jdbcTemplate.queryForObject("select count(1) count from meeting_join where c_id=?",Long.class,id);
    }

    public Integer isCome(Long uid, Long cid) {
        return jdbcTemplate.queryForObject("select count(1) count from meeting_join where u_id=? and c_id = ?",Integer.class,uid,cid);
    }

    public void comeMeeting(Long uid, Long cid) {
        jdbcTemplate.update("insert into meeting_join values (?,?)",uid,cid);
    }

    public void unComeMeeting(Long uid, Long cid) {
        jdbcTemplate.update("delete from meeting_join where u_id = ? and c_id = ? ",uid,cid);
    }

    public void addMeeting(Meeting meeting) {
        jdbcTemplate.update("insert into meeting values(null,?,?,?,?,?,?,?,?,?)",
                meeting.getDeptName(),
                meeting.getDeptId(),
                meeting.getTitle(),
                meeting.getContent(),
                meeting.getPublishDate(),
                meeting.getStartTime(),
                meeting.getEndTime(),
                meeting.getStatus(),
                meeting.getMakeUser()
        );
    }
}
